# -*- coding: utf-8 -*-
import sqlite3

_cfg_file_path = "_scfg.db"

def setcfgfile(path):
    _cfg_file_path = path

def cfggetint(key):
    v = cfgget(key)
    if v:
        return int(v)
    return 0

def cfgget(key):
    try:
        conn = sqlite3.connect(_cfg_file_path)
        cursor = conn.cursor()

        cursor.execute('SELECT * FROM KEYVAL WHERE key=?', (key,))
        row = cursor.fetchone()
        cursor.close()
        if not row:
            return None
        return row[1]
    except sqlite3.OperationalError as e:
        print(e)
        return None

def cfgset(key, val):
    conn = sqlite3.connect(_cfg_file_path)
    cursor = conn.cursor()
    cursor.execute('CREATE TABLE IF NOT EXISTS  KEYVAL (key varchar(128) primary key, val varchar(1024))')
    cursor.execute('INSERT OR REPLACE INTO KEYVAL (key, val) values (?,?)', (key, val))
    conn.commit()
    cursor.close()

    assert cfgget(key)==val


